﻿using NPoco;
using System;
using System.Data.Common;
using System.Diagnostics;

namespace ServiceKit
{
    public class WonderDataBase : Database
    {

        private AuditDbInfo auditInfo;
        private Stopwatch actionStopwatch;
        public WonderDataBase(string connectionString, DatabaseType databaseType, DbProviderFactory provider) : base(connectionString, databaseType, provider) { }

        protected override void OnException(Exception exception)
        {
            actionStopwatch.Stop();
            auditInfo.EndTime = DateTime.Now;
            auditInfo.ExecutionDuration = Convert.ToInt32(actionStopwatch.Elapsed.TotalMilliseconds);
            auditInfo.HasException = true;
            auditInfo.SQL = this.LastSQL;
            auditInfo.Exception = exception.ToString();
            Log.Save(auditInfo);
            base.OnException(exception);
        }

        protected override void OnExecutedCommand(DbCommand cmd)
        {
            actionStopwatch.Stop();
            auditInfo.EndTime = DateTime.Now;
            auditInfo.ExecutionDuration = Convert.ToInt32(actionStopwatch.Elapsed.TotalMilliseconds);
            auditInfo.HasException = false;
            Log.Save(auditInfo);
            base.OnExecutedCommand(cmd);
        }

        protected override void OnExecutingCommand(DbCommand cmd)
        {
            string sql = base.FormatCommand(cmd);
            actionStopwatch = Stopwatch.StartNew();
            auditInfo = new AuditDbInfo
            {
                DataSource = cmd.Connection.DataSource,
                DataBase = cmd.Connection.Database,
                BeginTime = DateTime.Now,
                SQL = sql
            };
            base.OnExecutingCommand(cmd);
        }
    }
}
